﻿using Examination.Args;
using Examination.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Examination.Filter
{
    /// <summary>
    /// 系统管理员过滤器
    /// </summary>
    public class WebVerificationSysAdminFilterAttribute : Attribute, IActionFilter
    {
        private readonly DataContext _dataContext;
        private readonly IArgsExtend _argsUser;

        public WebVerificationSysAdminFilterAttribute(DataContext dataContext, IArgsExtend argsUser)
        {
            _dataContext = dataContext;
            _argsUser = argsUser;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            string userId = context.HttpContext.Session.GetString("userId");
            if (String.IsNullOrEmpty(userId))
            {
                context.Result = new JsonResult(ResponseData.ValidationFailed());
            }
            else
            {
                User user = _dataContext.Users.FirstOrDefault(u => u.Id == Convert.ToInt32(userId));
                if (user == null)
                {
                    context.Result = new JsonResult(ResponseData.ValidationFailed());
                }
                else
                {
                    if(user.Type == UserType.System)
                    {
                    ((ArgsExtend)_argsUser).User = user;

                    }
                    else
                    {
                        context.Result = new JsonResult(ResponseData.NoPermission());
                    }
                }
            }
        }

    }
}
